<?php
/**
 * Created by PhpStorm.
 * User: AORUS
 * Date: 2022/2/14
 * Time: 10:55
 */

namespace app\admin\controller;

use app\admin\common\Base;
use app\admin\model\User as UserModel;

class User extends Base {
    public function index($page = 1, $limit = 10, $keyword = ''){
        if (request()->isPost()){

            //排除超管账号
            $where[] = ['id','not in',[1,2]];

            if (!empty($keyword)){
                $where[] = ['name|username','like','%'.$keyword.'%'];
            }
            $where[] = ['is_del','=',0];

            $data = $this->getListData('user',$where,'id','asc',$page,$limit);
            return json(['code'=>'suc','msg'=>'数据请求成功','count'=>$data['count'],'data'=>$data['list'],'current_page'=>$page]);
        }

        return $this->fetch();
    }

    /**
     * 新增
     * @return mixed|\think\response\Json
     */
    public function add(){
        if (request()->isPost()){
            $model = new UserModel();
            $result = $model->add();
            if ($result['code']){
                $code = 'suc';
                insert_system_log('添加新账号：'.input('post.username'));
            }else{
                $code = 'err';
            }
            return json(['code' => $code, 'msg' => $result['msg']]);

        }

        return $this->fetch();
    }

    /**
     * 编辑
     * @param $id 加密的账号id
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id){
        $user = db('user')->where('id',$id)->find();
        if (request()->isPost()){
            $code = 'err';
            $msg = '';
            $data = input('post.');
            if (!empty($data['password'])){
                if ($data['password'] != $data['repassword']){
                    return json(['code' => 'err','msg' => '两次密码不一致']);
                }else{
                    $data['password'] = qa_encrtyp($data['password']);
                }
                unset($data['id']);
                $model = new UserModel();
                $result = $model->allowField(true)->save($data,['id' => $id]);
                if ($result){
                    $code = 'suc';
                    $msg = '编辑账号信息成功';
                    insert_system_log('编辑账号：'.$user['username'] . '，ID：' . $user['id']);
                }else{
                    $msg = '编辑账号信息失败';
                }
            }else{
                $msg = '无需修改';
            }
            return json(['code' => $code, 'msg' => $msg]);

        }
        $this->assign('user',$user);
        return $this->fetch();
    }

    /**
     * 删除
     * @param $id
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del($id){
        if (is_post()){
            //开启事务
            db()->startTrans();
            try{
                db('user')->where('id',$id)->delete();
                db('user_role')->where('user_id',$id)->delete();
                insert_system_log('删除账号：' . $id);
                //提交事务
                db()->commit();
                return json(['code' => 'suc','msg' => '删除成功']);
            }catch (\Exception $e){
                //事务回滚
                db()->rollback();
                return json(['code' => 'err','msg' => '删除失败']);
            }
        }
    }

    /**
     * 变更账号状态
     * @param $type
     * @param $id
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function changeStatus($type,$id){
        $data['status'] = 1;
        $msg = '账号已启用';

        $account = db('user')->where('id',$id)->value('username');
        $system_log_msg = '启用账号：'.$account;
        if ($type == 2){
            $data['status'] = 0;
            $msg = '账号已禁用';
            $system_log_msg = '禁用账号：'.$account;
        }

        $result = db('user')->where('id',$id)->update($data);
        if ($result){
            insert_system_log($system_log_msg);
            return json(['code' => 'suc','msg' => $msg]);
        }else{
            return json(['code' => 'err','msg' => '系统繁忙，请重试']);

        }
    }

    public function allotRole($id){
        $account_info = db('user')->where('id',$id)->find();
        if (request()->isPost()){
            $check_role = input('post.check_role');
            if (!empty($check_role)){
                $check_role = array_unique($check_role);
                $data = [];
                foreach ($check_role as $k => $v){
                    $item['role_id'] = intval($v);
                    $item['user_id'] = intval($id);
                    array_push($data,$item);
                }
                db('user_role')->where('user_id',$id)->delete();
                $result = db('user_role')->insertAll($data);
            }else{
                $result = db('user_role')->where('user_id',$id)->delete();
            }
            if ($result){
                insert_system_log('分配账号角色，账号：' . $account_info['name'] . '，ID：' . $account_info['id']);
                return json(['code' => 'suc', 'msg' => '账号角色分配成功']);
            }else{
                return json(['code' => 'err', 'msg' => '账号角色分配失败']);
            }
        }

        //系统中全部角色
        $role_list = db('role')->where('status',1)->field('id,name')->select();

        //账号拥有的角色
        $user_role = db('user_role')->where('user_id',$id)->column('role_id');

        $this->assign('user_role_json',json_encode($user_role));
        $this->assign('user_node',$user_role);
        $this->assign('role_list',$role_list);
        $this->assign('account_info',$account_info);
        return $this->fetch();
    }

    /**
     * 获取当前账号拥有的权限
     * @return \think\response\Json
     */
    public function userNodeList(){
        $user_id = intval(get_user_id());
        $user_role = db('user_role')->where('user_id',$user_id)->column('role_id');
        $role_node = db('role_node')->where('role_id','in',$user_role)->column('node_id');

        $user_node = db('user_node')->where('user_id',$user_id)->column('node_id');

        $node_list = array_merge($user_node,$role_node);

        return json(['code' => 'suc','msg' => '请求数据成功','data' => $node_list]);
    }

    /**
     * 个人信息
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function personal(){
        $user_id = get_user_id();
        $user = db('user')->where('id',$user_id)->find();
        $this->assign('user',$user);
        return $this->fetch();
    }

    /**
     * 修改个人信息
     * @param $data
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editPersonalInfo($data){
        if (request()->isPost()){
            $user_id = intval(get_user_id());
            $password = $data['password'];
            $repassword = $data['repassword'];
            if (!empty($password)){
                if ($password == $repassword){
                    if (pwd_check($password)){
                        $update['password'] = qa_encrtyp($password);
                        $result = db('user')->where('id',$user_id)->update($update);
                        if ($result){
                            session('u_id',null);
                            return json(['code' => 'suc', 'msg' => '修改成功']);
                        }else{
                            return json(['code' => 'err', 'msg' => '修改失败']);
                        }
                    }else{
                        return json(['code' => 'err', 'msg' => '密码长度为6-20位字符，由英文字母和数字组成']);
                    }
                }else{
                    return json(['code' => 'err', 'msg' => '两次密码不一致']);
                }
            }

        }else{
            $this->error('非法请求！');
        }
    }
}